<template>
  <section>
    <!--工具条-->
    <el-col :span="24" class="toolbar" style="padding-bottom: 0px;">
      <el-form :inline="true">
        <el-form-item>
          <el-input v-model="keyword" placeholder="宠物名称"></el-input>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" v-on:click="keywordQuery">查询</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="handleAdd">新增</el-button>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" @click="onsale">上架</el-button>
          <el-button type="primary" @click="offsale">下架</el-button>
        </el-form-item>
      </el-form>
    </el-col>


    <!--列表 - 展示数据-->
    <!--
         :data="pets"  - 分页数据
         highlight-current-row  - 鼠标所在行高亮
         v-loading="listLoading"  - 加载框
         @selection-change="selsChange" - 批量操作
    -->
    <el-table :data="pets" highlight-current-row v-loading="listLoading" @selection-change="selsChange"
              style="width: 100%;">
      <el-table-column type="selection" width="55">
      </el-table-column>
      <el-table-column type="index" width="60">
      </el-table-column>
      <el-table-column prop="name" label="宠物名称">
      </el-table-column>
      <el-table-column prop="costprice" label="成本价格">
      </el-table-column>
      <el-table-column prop="saleprice" label="市场价格">
      </el-table-column>
      <el-table-column prop="typeName" label="宠物类型">
      </el-table-column>
      <el-table-column label="启用状态" sortable>
        <template scope="scope">
          <span style="color: #11b95c" v-if="scope.row.state==1">上 架</span>
          <span style="color: red" v-else>下 架</span>
        </template>
      </el-table-column>
      <el-table-column prop="offsaletime" label="下架时间">
      </el-table-column>
      <el-table-column prop="onsaletime" label="销售时间">
      </el-table-column>
      <el-table-column prop="createtime" label="创建时间">
      </el-table-column>
      <el-table-column prop="shopName" label="所在店铺">
      </el-table-column>
      <el-table-column prop="username" label="领养人">
      </el-table-column>
      <el-table-column prop="searchMasterMsgId" label="宠物来源">
        <template scope="scope">
          <span style="color: #11b95c" v-if="scope.row.searchMasterMsgId">用户寻主</span>
          <span style="color: #00d2f1" v-else>店铺饲养</span>
        </template>
      </el-table-column>
      <el-table-column label="操作" width="150">
        <template scope="scope">
          <el-button size="small" @click="handleSave(scope.$index, scope.row)">编辑</el-button>
          <el-button type="danger" size="small" @click="handleDel(scope.$index, scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>

    <!--工具条 - 批量删除 + 分页栏 -->
    <el-col :span="24" class="toolbar">
      <el-button type="danger" @click="batchRemove" :disabled="this.sels.length===0">批量删除</el-button>
      <el-pagination layout="prev, pager, next" @current-change="handleCurrentChange"
                     :current-page="currentPage" :page-size="pageSize" :total="totals" style="float:right;">
      </el-pagination>
    </el-col>

    <!--添加和修改界面的对话框-->
    <el-dialog :title="title" :visible.sync="saveFormVisible" :close-on-click-modal="false" width="80%">
      <el-form :model="saveForm" label-width="80px" :rules="saveFormRules" ref="saveForm">
        <el-form-item label="宠物名称" prop="name">
          <el-input v-model="saveForm.name" auto-complete="off"></el-input>
        </el-form-item>
        <el-form-item label="成本价格">
          <el-input v-model="saveForm.costprice" auto-complete="off" placeholder="0"></el-input>
        </el-form-item>
        <el-form-item label="市场价格">
          <el-input v-model="saveForm.saleprice" auto-complete="off" placeholder="0"></el-input>
        </el-form-item>
        <el-form-item label="宠物类型" prop="typeId">
          <el-cascader v-model="saveForm.typeId"
                       :options="petTypeTree"
                       :props="{
                checkStrictly: true,
                label:'name',   // 级联框显示那个属性的值
                value:'id'      // 回显时需要,回传值的时候也需要
              }" clearable>
          </el-cascader>
        </el-form-item>
        <el-form-item label="宠物美照">
          <el-upload
              class="upload-demo"
              action="http://localhost:8080/fastDfs"
              :on-remove="handleRemove"
              :on-success="handleSuccess"
              :file-list="fileList"
              list-type="picture">
            <el-button size="small" type="primary">点击上传</el-button>
            <div slot="tip" class="el-upload__tip">只能上传jpg/png文件，且不超过500kb</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="宠物状态">
          <el-radio-group v-model="saveForm.state">
            <el-radio class="radio" :label="1">上 架</el-radio>
            <el-radio class="radio" :label="0">下 架</el-radio>
          </el-radio-group>
        </el-form-item>
        <!--        <el-form-item label="下架时间">-->
        <!--          <el-input v-model="saveForm.offsaletime" auto-complete="off"></el-input>-->
        <!--        </el-form-item>-->
        <!--        <el-form-item label="销售时间">-->
        <!--          <el-input v-model="saveForm.onsaletime" auto-complete="off"></el-input>-->
        <!--        </el-form-item>-->
        <el-form-item label="所在店铺">
          <el-select v-model="saveForm.shopId" placeholder="请选择">
            <el-option
                v-for="item in shops"
                :label="item.name"
                :value="item.id">
              <span style="float: left">{{ item.name }}</span>
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="简介" prop="intro">
          <!-- v-if="saveForm.petDetail" 修改v-model绑定对象报错问题，v-if对需要显示的数据判断下 -->
          <quill-editor  v-model="saveForm.petDetail.intro" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
        <el-form-item label="领养须知" prop="orderNotice" >
          <quill-editor  v-model="saveForm.petDetail.adoptNotice" v-if="saveForm.petDetail" :options="quillOption">
          </quill-editor>
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click.native="saveFormVisible=false">取消</el-button>
        <el-button type="primary" @click.native="saveSubmit" :loading="saveLoading">提交</el-button>
      </div>
    </el-dialog>

  </section>
</template>

<script>
//引入Vue的ueditor的资源
import {quillEditor} from "vue-quill-editor"; //调用编辑器
import 'quill/dist/quill.core.css';
import 'quill/dist/quill.snow.css';
import 'quill/dist/quill.bubble.css';
//富文本编辑框集成FastDfs后导入并使用
import quillConfig from '../../common/js/quill-config';

//添加组件
export default {
  components: {
    quillEditor
  },
  quillOption: quillConfig,
  methods: {
    //1.获取分页数据的方法
    getPets() {
      let para = {
        currentPage: this.currentPage,
        pageSize: this.pageSize,
        //高级查询参数传递
        keyword: this.keyword
      };
      //加载框显示
      this.listLoading = true;
      this.$http.post("/pet", para).then(res => {
        //赋值总数量 - 计算分页栏s
        this.totals = res.data.totals;
        this.pets = res.data.data;
        //加载完数据隐藏加载框
        this.listLoading = false;
        //NProgress.done();
      }).catch(res => {
        //隐藏加载框
        this.listLoading = false;
        this.$message.error("网络错误，请稍后重试")
      })
    },


    //2.获取当前页数的方法
    handleCurrentChange(val) {
      this.currentPage = val;
      this.getPets();
    },


    //3.高级查询调用的方法
    keywordQuery() {
      //将当前页置为第一页，防止出现前端传输的currentpage导致后端分页错误
      this.currentPage = 1;
      this.getPets();
    },


    //4.删除单条数据的方法
    handleDel: function (index, row) {
      this.$confirm('确认删除该记录吗?', '提示', {
        type: 'warning'
      }).then(() => {//点击确定框 执行then里面的逻辑
        this.listLoading = true;
        //row 行对象   row.id行对象的id属性值 - 发送删除请求
        this.$http.delete('/pet/' + row.id).then(res => {
          //关闭加载框
          this.listLoading = false;
          //回调函数res.data.success获取操作结果
          if (res.data.success) {//如果操作成功
            this.$message.success("删除成功");
            if (((this.currentPage - 1) * this.pageSize + 1) == this.totals && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
            this.getPets();
          } else {
            this.$message.error("网络连接异常,请重试")
          }
        });
      }).catch(res => {
      })
    },


    //5.设置勾选的数据数组的方法
    selsChange: function (sels) {
      this.sels = sels;
    },

    //6.批量删除
    batchRemove: function () {
      //sels.map(item => item.id) - item(数组中的每一个对象) - 返回的还是数组
      var ids = this.sels.map(item => item.id);//获取到数组中每一个对象的id
      this.$confirm('确认删除选中记录吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.patch("/pet", ids).then(res => {
          if (res.data.success) {
            this.$message.success('删除成功');
            if ((this.currentPage - 1) * this.pageSize + ids.length == this.totals && this.currentPage != 1) {
              this.currentPage = this.currentPage - 1;
            }
          } else {
            this.$message.error('网络请求超时,请检查网络后重试');
          }
          this.getPets();
        }).catch(res => {
          this.$message.error('网络请求超时,请检查网络后重试');
        })
      });
    },


    //7.点击编辑弹出对话框
    handleSave: function (index, row) {
      //动态设置对话框标题
      this.title = "编辑";
      //将当前行对象克隆到一个新对象中
      this.saveForm = Object.assign({}, row);
      //将当前resources赋值到fileList中
      this.copyResoucestoFileList();

      this.getPetTypeTree();
      this.getShops();
      //打开对话框
      this.saveFormVisible = true;
    },


    //8.点击新增弹出对话框
    handleAdd: function () {
      //动态设置对话框标题
      this.title = "添加";
      //点击添加应该将对话框表单数据重置
      this.saveForm = {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        },
      };
      this.fileList = [];
      this.getPetTypeTree();
      this.getShops();
      //打开对话框
      this.saveFormVisible = true;
    },


    //9.点击对话框的保存提交数据
    saveSubmit: function () {
      //所有表单验证的saveForm表单验证
      //validate获得表单验证是否通过 - 所有表单项验证通过才为true
      this.$refs.saveForm.validate((valid) => {
        if (valid) {
          this.$confirm('确认提交吗？', '提示', {}).then(() => {
            //打开提交的加载框
            this.saveLoading = true;
            //this.saveForm.resources = this.fileList.toString();
            let para = Object.assign({}, this.saveForm);
            console.log(para);
            // //前端数据会有4种情况：单个数字，空数组，null，有值的数组
            // //对表单的部门树数据进行处理
            if (para.typeId == null || para.typeId.length == 0) {
              para.typeId = null;
            } else if (para.typeId.length) {
              para.typeId = para.typeId[para.typeId.length - 1];
            }
            console.log(this.saveForm)
            console.log("-------------------------------------")
            console.log(para);
            this.$http.put('/pet', para).then(res => {
              //如果操作成功
              if (res.data.success) {
                this.$message.success('操作成功');
                //关闭提交的加载框
                this.saveLoading = false;
              } else {
                this.$message.error('网络错误,请检查网络连接');
              }
              //刷新列表数据
              this.getPets();
              //关闭对话框
              this.saveFormVisible = false;
              this.saveLoading = false;
            }).catch(res => {
              this.$message.error('网络错误,请检查网络连接');
              this.saveFormVisible = false;
              this.saveLoading = false;
            })
          });
        }
      });
    },
    //获取类型树
    getPetTypeTree() {
      this.$http.get("/petType/petTypeTree").then(res => {
        this.petTypeTree = res.data;
      })
    },
    //获取所有店铺的方法
    getShops() {
      this.$http.get("/shop").then(res => {
        this.shops = res.data;
      })
    },

    //文件上传的业务逻辑 - 上传后给模型数据shop的logo赋值
    handleSuccess(response, file, fileList) {
      var resources = this.saveForm.resources;

      //如果resouces中有图片都没有上传就直接等于
      if (resources) {
        //上传第二张开始就拼接','+图片路径
        this.saveForm.resources += "," + response.obj;
      } else {
        //反之，则是第一次上传图片
        this.saveForm.resources = response.obj;
      }

      //将resouces中的图片信息拷贝到fileList中
      this.copyResoucestoFileList();

    },

    //文件删除的业务逻辑
    handleRemove: function (file, fileList) {
      //url = http://123.207.27.208/group1/M00/03/BF/CgAIC2PvMlOAIT_EAABUaCz1tQw421.jpg
      var url = file.url;
      //从/group所在下标开始截取到末尾  path = /group1/M00/03/BF/CgAIC2PvMlOAIT_EAABUaCz1tQw421.jpg
      var path = url.substring(url.indexOf("/group"));
        this.$http.delete("/fastDfs?path=" + path).then(res => {
          if (res.data.success) {
            //重新给resources赋值
            var resources = this.saveForm.resources;
            //如果resources中有值
            if(resources){
              //用，切割
              let resourceArr = resources.split(",");
              //遍历数组
              for (var i=0;i<resourceArr.length;i++){
                //如果删除的图片和遍历出来的这张图片一致
                if(path==resourceArr[i]){
                  //通过splice删除这张图片 splice(a,b); a=要删除的元素所在下标 b=删除几个元素
                  resourceArr.splice(i,1);
                  //跳出循环
                  break;
                }
              }
              //数组每个元素用逗号隔开添加进resources
              this.saveForm.resources = resourceArr.join(",");

              //将resources中的最新数据copy给fileList
              this.copyResoucestoFileList();
            }
            this.$message.success("删除成功")
          } else {
            this.$message.error("删除失败,请重试")
          }
        }).catch(res => {
          this.$message.error("删除失败,请检查网络后重试")
        })
    },

    //刷新fileList的公共方法
    copyResoucestoFileList(){
      this.fileList=[];
      //如果resources有值
      var resources = this.saveForm.resources;
      if(resources){
        //遍历出每一个resouce
        for (var resource of resources.split(",")) {
          //将每一张图片对象添加进fileList中
          this.fileList.unshift({url: this.imgPrefix+resource});
        };
      }
    },

    //点击上架执行的方法
    onsale(){
      if(!this.sels || this.sels.length<1 ){
        this.$message.warning("请选择要上架的数据");
        return ;
      }
      //sels.map(item => item.id) - item(数组中的每一个对象) - 返回的还是数组
      var ids = this.sels.map(item => item.id);//获取到数组中每一个对象的id
      this.$confirm('确认上架选中数据吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post("/pet/onsale",ids).then(res=>{
          res = res.data
          if(res.success){
            this.$message.success("上架成功");
            this.getPets();
          }else {
            this.$message.error(res.msg);
          }
          this.listLoading = false;
        }).catch(res=>{
          this.$message.error('网络请求超时,请检查网络后重试【400，404，405】');
          this.listLoading = false;
        })
      });
    },

    //点击下架执行的方法
    offsale(){
      if(!this.sels || this.sels.length<1 ){
        this.$message.warning("请选择要下架的数据");
        return ;
      }
      //sels.map(item => item.id) - item(数组中的每一个对象) - 返回的还是数组
      var ids = this.sels.map(item => item.id);//获取到数组中每一个对象的id
      this.$confirm('确认下架选中数据吗？', '提示', {
        type: 'warning'
      }).then(() => {
        this.listLoading = true;
        this.$http.post("/pet/offsale",ids).then(res=>{
          res = res.data
          if(res.success){
            this.$message.success("下架成功");
            this.getPets();
          }else {
            this.$message.error("下架失败");
          }
          this.listLoading = false;
        }).catch(res=>{
          this.$message.error('网络请求超时,请检查网络后重试【400，404，405】');
          this.listLoading = false;
        })
      });
    },

  },
  data() {
    return {
      //富文本编辑器模型数据 - 集成FastDfs
      quillOption: quillConfig,

      //列表显示图片的前缀
      imgPrefix: "http://123.207.27.208",
      //1.分页查询的列表数据
      pets: [],      //列表数据
      listLoading: false,   //加载框默认false
      //2.分页栏数据
      totals: 0,             //数据总数
      pageSize: 5,           //每页显示数据条数
      currentPage: 1,        //当前页数

      //2.高级查询的相关数据
      keyword: '',

      //4.批量删除的相关数据
      sels: [],             //列表选中列

      //3.添加或修改的的相关数据
      title: '',             //对话框标题
      saveFormVisible: false,//对话框是否显示 - false 默认不显示
      saveLoading: false,   //加载框是否显示 - 默认不显示
      saveFormRules: {      //表单项验证 - 需要验证的表单项加入进去
        name: [
          {required: true, message: '请输入宠物名称', trigger: 'blur'}//blur - 失去焦点
        ],
        typeId: [
          {required: true, message: '请选择宠物类型', trigger: 'blur'}//blur - 失去焦点
        ],
      },
      //4.对话框界面模型数据
      saveForm: {
        id: null,
        name: '',
        costprice: 0,
        saleprice: 0,
        typeId: null,
        resources: '',
        state: 0, //默认下架 - 前台看不见这个宠物 - 审核之后才能上架
        shopId: null,
        petDetail:{  //与后端实体类一致
          intro: '',
          adoptNotice: ''
        },
      },
      //宠物类型数
      petTypeTree: [],
      //所有店铺信息
      shops: [],
      //文件上传相关数据
      fileList: [],

    }

  },
  //钩子函数 - 相当于页面加载事件
  mounted() {
    this.getPets();
  },
  watch: {
    //1.监听saveFormVisible的变化
    saveFormVisible: {
      handler() {
        //如果关闭了对话框
        if (!this.saveFormVisible) {
          //则重置对话框表单验证的函数
          this.$refs['saveForm'].resetFields();
        }
      }
    },
  }
}

</script>
<style scoped>

</style>